<template>
  <div class="dataCleaning">
    <el-row :gutter="20" style="height: 100%;">
      <el-col :span="12">
        <!-- style="width: 100%;height: calc(100vh - 60px);" -->
        <div class="grid-content ep-bg-purple">
          <h4 class="header_1">清洗配置</h4>
          <div class="fileSelection">
            <div class="title">选择数据文件</div>
            <el-input
              v-model="fileName"
              style="max-width: 100%;margin-top: 15px;"
              class="input-with-select"
            >
              <template #append>
                <!-- <el-button @click="handleFileUpload">...</el-button> -->
                <el-upload
                  ref='fileRef'
                  class="upload-demo"
                  action="#"
                  :limit="1"
                  accept=".mat,.xlsx"
                  :auto-upload="false"
                  :show-file-list='false'
                  :on-change="handleChange"
                  :on-exceed="handleExceed"
                >
                  <template #trigger>
                    <el-button type="primary">...</el-button>
                  </template>
                </el-upload>
              </template>
            </el-input>
          </div>
          <div class="cleaningWay">
            <div class="title">清洗方式</div>
            <el-select v-model="c_way" style="width: 100%;margin-top: 15px;">
              <el-option
                v-for="item in cleaningWay_options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <!-- <div class="storePath">
            <div class="title">保存路径</div>
            <el-input
              v-model="s_path"
              style="max-width: 100%;margin-top: 15px;"
              class="input-with-select"
            >
              <template #append>
                <el-button @click="handleSavePath">...</el-button>
              </template>
            </el-input>
          </div> -->
          <div class="btns">
              <el-button @click="uploadBtn" type="primary" style="padding: 10px 40px;" :disabled="isDisabled"
              >{{ clean_status }}</el-button>
            <!-- <el-button type="warning" style="padding: 10px 20px">暂停</el-button>
            <el-button type="danger" style="padding: 10px 20px">结束</el-button> -->
          </div>
        </div>
      </el-col>
      <!-- <el-col :span="0.5"></el-col> -->
      <el-col :span="12">
        <div class="grid-content ep-bg-purple" style="padding-top: 20px">
          <div class="over_btn">
            <el-tag :type="tagType" style="padding: 15px 45%; font-size: 18px">
              {{ c_status }}
            </el-tag>
          </div>
          <div ref="chartRef" class="chart"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted,computed } from "vue";
import { useECharts } from "@pureadmin/utils";
import { codeClean } from '@/api/dataProcessing'
import { genFileId } from 'element-plus'

const fileName = ref("");
const c_way = ref(1);
const s_path = ref("");
const c_status = ref("未清洗");
const clean_status = ref("开始清洗")
const isDisabled = ref(false)
const chartYName = ref("齿轮振动传感器加速度数据")
const cleaningWay_options = [
  {
    value: 1,
    label: "缺失值填充"
  },
  {
    value: 0,
    label: "重复值删除"
  },
];

onMounted(() => {
  render();
});

const chartRef = ref();
const chartData = ref([
  {
    data: [120, 132, 101, 134, 90, 230, 210],
    name: '原始数据'
  },
  {
    data: [220, 182, 191, 234, 290, 330, 310],
    name: '修复数据'
  }
])
const { setOptions, resize } = useECharts(chartRef, {});
const render = () =>
  setOptions({
    // color: ["rgb(12, 120, 225)", "rgb(255, 153, 0)"],
    title: {
      // text: '随便填写',
      top: "5%",
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: "axis"
    },
    legend: {
      right: "15%",
      data: ["原始数据", "修复数据"],
      icon: "roundRect",
      top: "5%",
      textStyle: {
        fontSize: 14
      }
    },
    grid: {
      top: "20%",
      left: "0%",
      right: "10%",
      bottom: "10%",
      containLabel: true
    },
    toolbox: {
      feature: {}
    },
    xAxis: {
      axisTick: {
        show: false
      },
      axisLabel: {
        margin: 15 // 调整刻度标签和坐标轴名称之间的间距
      },
      name: '数量',
      nameTextStyle: {
        color: "#303133",
        fontSize: 14,
        padding: [35, 0, 0, -45],
        verticalAlign: "top"
      },
      type: "category",
      boundaryGap: true,
      // data: ["1", "2", "3", "4", "5", "6", "7", "8"]
    },
    yAxis: {
      name: chartYName.value,
      type: "value",
      nameRotate: 0.1
    },
    series: [
      {
        name: '原始数据',
        type: "line",
        data: chartData.value[0].data,
        symbol: "none", // 设置标记点形状为无
        showSymbol: false, // 不显示标记点
        // lineStyle: {
        //   shadowBlur: 5,
        //   shadowColor: "rgba(12, 120, 225, 0.5)",
        //   shadowOffsetY: 3
        // }
      },
      {
        name: '修复数据',
        type: "line",
        data: chartData.value[1].data,
        symbol: "none", // 设置标记点形状为无
        showSymbol: false, // 不显示标记点
        // lineStyle: {
        //   shadowBlur: 5,
        //   shadowColor: "rgba(255, 153, 0, 0.5)",
        //   shadowOffsetY: 3
        // }
      }
    ]
  });

  const changeYName = () => {
    if (c_way.value == 1) {
      if (fileName.value.split('.')[1] === "mat") {
        chartYName.value = "齿轮振动传感器加速度数据"
      }else if (fileName.value.split('.')[1] === "xlsx") {
        chartYName.value = "主轴转速数据"
      }
    }else if (c_way.value == 0) {
      chartYName.value = "主轴转速"
    }
  }

  let fileRef = ref()
  let fileUp = ref();
  // 选择文件时被调用，将他赋值给fileRef
  const handleChange = (file,fileList) => {
    fileRef.value = file
    fileName.value = file.name;
    fileUp.value = file;
  }

  // 覆盖前一个选择的
  const handleExceed = (files) => {
    fileRef.value.clearFiles()
    const file = files[0];
    file.uid = genFileId()
    fileRef.value.handleStart(file)
  }

  // 开始清洗
const uploadBtn = () => {
    chartData.value[0] = {}
    chartData.value[1] = {}
    if (fileUp.value) {
      changeYName();
      clean_status.value = "清洗中..."
      c_status.value = '清洗中....'
      isDisabled.value = true
      let formData = new FormData()
      console.log(fileUp.value)
      formData.append("method", c_way.value)
      formData.append("file", fileUp.value.raw)

      codeClean(formData).then(res => {
        if (res.status === 200) {
          console.log('-------',res.data)
          chartData.value[0].data = res.data.oridata;
          chartData.value[1].data = res.data.prodata;
          render();
          if (res.data.oridata.length > 0) {
            c_status.value = "清洗完成"
            clean_status.value = "开始清洗"
            isDisabled.value = false
          }
        } else {
          c_status.value = '清洗失败';
          clean_status.value = "开始清洗"
        }
      }).catch(error => {
        console.log(error)
      });
    }
  }


function handleFileUpload() {
  // 处理文件上传逻辑
  const inputElement = document.createElement("input");
  inputElement.type = "file";
  inputElement.accept = ".mat,.xlsx"; // 设置允许的文件类型
  inputElement.onchange = event => {
    const selectedFile = event.target.files[0];
    if (selectedFile) {
      // 检查文件类型
      const fileType = selectedFile.name.split('.').pop().toLowerCase();
      if (fileType !== 'mat' && fileType !== 'xlsx') {
        // 提示用户选择正确的文件类型
        alert("请选择 .mat 或 .xlsx 文件");
        return; // 中止上传
      }

      // 文件类型验证通过，更新界面显示选定的文件名
      file.value = selectedFile.name;
      // 可以根据需要将文件信息存储在其他变量中
    }
  };
  inputElement.click();
}

function handleSavePath() {
  // 处理保存路径逻辑
  const inputElement = document.createElement("input");
  inputElement.type = "file";
  inputElement.webkitdirectory = true; // 在 Chrome 中选择文件夹
  inputElement.multiple = false; // 只能选择一个文件夹
  inputElement.onchange = event => {
    const selectedPath = event.target.files[0].path;
    if (selectedPath) {
      s_path.value = selectedPath;
      // 可以根据需要将路径信息存储在其他变量中
    }
  };
  inputElement.click();
}

//计算属性
const tagType = computed(() => {
  if (c_status.value ==='未清洗') {
      return 'danger'
  }
  else if (c_status.value ==='清洗完成') {
    return 'success'
    }
})
</script>

<style lang="scss" scoped>
.dataCleaning {
  width: 100%;
  height: 100%;
  font-size: 16px;

  .grid-content {
    height: 100%;
    border-radius: 10px;
    box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
    background-color: #fff;
    margin-bottom: 0px;
    padding: 0 10px;
  }

  .header_1,
  .header_2 {
    width: 100%;
    height: 60px;
    line-height: 60px;
    padding-left: 20px;
    border-bottom: 1px solid #ccc;

  }
  .title{
    font-size: 15px;
  }
  .fileSelection,
  .cleaningWay,
  .storePath,
  .btns {
    width: 100%;
    height: 100px;
    line-height: 40px;
    padding-left: 20px;
    margin-top: 20px;

  }

  .over_btn {
    text-align: center;
    width: 100%;
  }

  .chart {
    width: 100%;
    height: 430px;
    margin-top: 20px;
  }
}
</style>
